export function initCanvas(canvas) {
    const ctx = canvas.getContext('2d');
    const dpr = window.devicePixelRatio || 1;
    const rect = canvas.getBoundingClientRect();
    canvas.width = rect.width * dpr;
    canvas.height = rect.height * dpr;
    ctx.setTransform(dpr, 0, 0, dpr, 0, 0);

    window.addEventListener('resize', () => {
        const rect = canvas.getBoundingClientRect();
        canvas.width = rect.width * dpr;
        canvas.height = rect.height * dpr;
        ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
        if (window.redrawAll) window.redrawAll();
    });
}

export function clearCanvas(ctx, width, height) {
    ctx.clearRect(0, 0, width, height);
}

// 常用坐标转换
export const AXIS_LEFT = 60;
export const AXIS_BOTTOM = 30;

export function freqToX(freq, canvas, view) {
    const plotW = canvas.width - AXIS_LEFT;
    const leftFreq = view.centerFreq - view.bandwidth / 2;
    const rightFreq = view.centerFreq + view.bandwidth / 2;
    return AXIS_LEFT + ((freq - leftFreq) / (rightFreq - leftFreq)) * plotW;
}

export function xToFreq(x, canvas, view) {
    const plotW = canvas.width - AXIS_LEFT;
    const leftFreq = view.centerFreq - view.bandwidth / 2;
    const rightFreq = view.centerFreq + view.bandwidth / 2;
    return leftFreq + ((x - AXIS_LEFT) / plotW) * (rightFreq - leftFreq);
}
// export function freqToX(freq, canvas, view) {
//     const plotW = canvas.width - AXIS_LEFT;
//     const left = view.centerFreq - view.bandwidth / 2;
//     return AXIS_LEFT + (freq - left) * (plotW / view.bandwidth);
// }
//
// export function xToFreq(x, canvas, view) {
//     const plotW = canvas.width - AXIS_LEFT;
//     const left = view.centerFreq - view.bandwidth / 2;
//     return left + (x - AXIS_LEFT) * (view.bandwidth / plotW);
// }
export function dbToY(db, canvas, view) {
    const h = canvas.height - AXIS_BOTTOM;
    const t = (view.maxDb - db) / (view.maxDb - view.minDb);
    return t * h;
}